package com.lantosec.hmrp.modules.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.config.InitDataListener;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.kit.Result;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.core.util.DateUtils;
import com.lantosec.hmrp.core.util.UUIDUtils;
import com.lantosec.hmrp.modules.supplier.entity.*;
import com.lantosec.hmrp.modules.supplier.mapper.SupplierInfoMapper;
import com.lantosec.hmrp.modules.supplier.service.ISupplierAccessoryService;
import com.lantosec.hmrp.modules.supplier.service.ISupplierEntryService;
import com.lantosec.hmrp.modules.supplier.service.ISupplierInfoService;
import com.lantosec.hmrp.modules.supplier.service.ISupplierLinkmanService;
import com.lantosec.hmrp.modules.supplier.vo.SupplierAccessoryVO;
import com.lantosec.hmrp.modules.supplier.vo.SupplierBadVO;
import com.lantosec.hmrp.modules.supplier.vo.SupplierInfoVO;
import com.lantosec.hmrp.modules.supplier.vo.SupplierLinkmanVO;
import com.lantosec.hmrp.modules.system.entity.SysDept;
import com.lantosec.hmrp.modules.system.service.ISysDeptService;
import com.lantosec.hmrp.modules.system.service.ISysDictionariesService;
import com.lantosec.hmrp.modules.uploads.entity.SysUploads;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import com.lantosec.hmrp.modules.workflow.service.IWorkflowBusinessService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 供应商信息 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-02-20
 */
@Service
@Primary
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class SupplierInfoServiceImpl extends ServiceImpl<SupplierInfoMapper, SupplierInfo> implements ISupplierInfoService {

    @Autowired
    private ISysDictionariesService iSysDictionariesService;

    @Autowired
    private ISysUploadsService iSysUploadsService;

    @Autowired
    private ISupplierEntryService iSupplierEntryService;

    @Autowired
    private ISupplierLinkmanService iSupplierLinkmanService;

    @Autowired
    private ISupplierAccessoryService supplierAccessoryService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private IWorkflowBusinessService workflowBusinessService;

    @Autowired
    private ISupplierAccessoryService iSupplierAccessoryService;

    /**
     * 根据条件查询供应商信息（分页）
     * @param page
     * @param supplierName
     * @param supplierType
     * @param entryState
     * @return
     */
    @Override
    public PageVO<SupplierInfoVO> querySupplierInfoAll(PageVO<SupplierInfo> page, String supplierName, String supplierType, String entryState) {
        PageVO<SupplierInfoVO> pageVO = baseMapper.querySupplierInfoAll(page,supplierName,supplierType,entryState);
        List<SupplierInfoVO> list = pageVO.getRecords();
        list.forEach(parm->{
            this.getDictionariesShowName(parm);
        });
        pageVO.setRecords(list);
        return pageVO;
    }

    /**
     * 分页查询本部门下的供应商信息
     * @param page
     * @param supplierName
     * @param supplierType
     * @param deptId
     * @return
     */
    @Override
    public PageVO<SupplierInfoVO> querySupplierInfoByDept(PageVO<SupplierInfo> page, String supplierName, String supplierType, String deptId) {
        PageVO<SupplierInfoVO> pageVO =baseMapper.querySupplierInfoByDept(page,supplierName,supplierType,deptId);
        List<SupplierInfoVO> list = pageVO.getRecords();
        list.forEach(parm->{
            this.getDictionariesShowName(parm);
        });
        pageVO.setRecords(list);
        return pageVO;
    }

    /**
     * 查询当前用户名的部门id
     * @param userId
     * @return
     */
    @Override
    public String getDeptId(String userId) {
        return baseMapper.getDeptId(userId);
    }

    /**
     * 查询供应商详情信息
     * @param supplierCode
     * @return
     */
    @Override
    public SupplierInfoVO querySupplierInfoById(String supplierCode,String entryState) {
        SupplierInfoVO supplierInfoVO = baseMapper.querySupplierInfoById(supplierCode);
        String supplier = supplierInfoVO.getSupplierCode();
        String supplierType = iSupplierEntryService.querySupplierType(supplier,entryState);
        supplierInfoVO.setSupplierType(supplierType);
        supplierInfoVO = this.getDictionariesShowName(supplierInfoVO);
        //查询供应商的不良记录状态
        SupplierBadVO supplierBadVO = baseMapper.getSupplierBadIfno(supplier);
        if(Objects.nonNull(supplierBadVO)){
            if(supplierBadVO.getStopFlag() == 1){
                supplierInfoVO.setHandleStateName("暂停采购");
            }
            if(supplierBadVO.getBlacklistFlag() == 1){
                supplierInfoVO.setHandleStateName("纳入企业黑名单");
            }
        }
        return supplierInfoVO;
    }

    /**
     * 新增供应商信息
     * @param supplier
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertSupplierInfo(Supplier supplier) {
        //封装一个bean包括SupplierInfo和SupplierLinkman和SupplierAccessory
        //新增供应商信息
        SupplierInfoVO supplierInfo = supplier.getSupplierInfo();
        Integer entryState = supplier.getEntryState();
        //添加创建人
        //获得redis中的用户名和id
        String userId = TokenUtil.getUserId();
        String name = TokenUtil.getName();
        supplierInfo.setCreateUserId(userId);
        supplierInfo.setCreateUser(name);
        //添加对应的部门id
        String deptId = TokenUtil.getDeptId();
        SysDept sysDept = iSysDeptService.getById(deptId);
        supplierInfo.setCreateDeptId(deptId);
        supplierInfo.setCreateDeptName(sysDept.getDeptName());
        //添加创建时间
        supplierInfo.setCreateTime(DateUtils.nowDate());

        //新增供应商准入信息
        saveSupplierEntry(supplierInfo, entryState,userId,name);

        //新增供应商联系人信息
        String linkmanId = saveSupplierLinkman(supplier, supplierInfo);
        //供应商基本信息表中关联联系人id
        supplierInfo.setLinkmanId(linkmanId);

        //查询省份和城市的名称
        String supplierProvince = supplierInfo.getSupplierProvince();
        if(StringUtils.isNotEmpty(supplierProvince)){
            String supplierProvinceName = iSysDictionariesService.getById(supplierProvince).getDictionariesShowName();
            if(StringUtils.isNotEmpty(supplierProvinceName)){
                supplierInfo.setSupplierProvince(supplierProvinceName);
            }
        }
        String supplierCity = supplierInfo.getSupplierCity();
        if(StringUtils.isNotEmpty(supplierCity)){
            String supplierCityName = iSysDictionariesService.getById(supplierCity).getDictionariesShowName();
            if(StringUtils.isNotEmpty(supplierCityName)){
                supplierInfo.setSupplierCity(supplierCityName);
            }
        }
        this.save(supplierInfo.convertToEntity());

        //新增资质附件
        saveSupplierAccessory(supplier, supplierInfo);
        return supplierInfo.getSupplierCode();
    }

    /**
     * 新增资质附件
     * @param supplier
     * @param supplierInfo
     */
    private void saveSupplierAccessory(Supplier supplier, SupplierInfoVO supplierInfo) {
        List<SupplierAccessoryVO> supplierAccessoryList = supplier.getSupplierAccessory();
        if(supplierAccessoryList != null && supplierAccessoryList.size() > 0){
            supplierAccessoryList.forEach(parm->{
                parm.setAccessoryId(UUIDUtils.get());
                parm.setSupplierCode(supplierInfo.getSupplierCode());
                //添加创建人
                supplierAccessoryService.save(parm.convertToEntity());
            });
        }
    }

    /**
     * 新增供应商联系人信息
     * @param supplier
     * @param supplierInfo
     */
    private String saveSupplierLinkman(Supplier supplier, SupplierInfoVO supplierInfo) {
        SupplierLinkman supplierLinkman = supplier.getSupplierLinkman().convertToEntity();
        supplierLinkman.setLinkmanId(UUIDUtils.get());
        //联系人表关联对应的供应商编码
        supplierLinkman.setSupplierCode(supplierInfo.getSupplierCode());
        //添加联系人创建时间
        supplierLinkman.setCreateTime(DateUtils.nowDate());
        iSupplierLinkmanService.save(supplierLinkman);
        return supplierLinkman.getLinkmanId();
    }

    /**
     * 新增供应商准入信息
     * @param supplierInfo
     * @param entryState
     * @param userId
     * @param name
     */
    private void saveSupplierEntry(SupplierInfoVO supplierInfo, Integer entryState,String userId,String name) {
        //新增供应商准入信息
        SupplierEntry supplierEntry = new SupplierEntry();
        supplierEntry.setEntryId(UUIDUtils.get());
        supplierEntry.setSupplierCode(supplierInfo.getSupplierCode());
        supplierEntry.setSupplierType(supplierInfo.getSupplierType());
        //有效期结束日期validity_end_date为申请时间+准入有效期月份
        //TODO
        supplierEntry.setValidityEndDate("2020-01-01");
        supplierEntry.setEntryState(supplierInfo.getEntryState());
        supplierEntry.setApplyTime(DateUtils.nowDate());
        supplierEntry.setApplyUserId(userId);
        supplierEntry.setApplyUser(name);
        if (entryState == 0) {
            supplierEntry.setEntryState(2);
            supplierEntry.setEntryTime(DateUtils.nowDate());

            // 发起流程
            String definitionKey = iSupplierEntryService.getSupplierEntryProcessKey();
            Boolean flag = workflowBusinessService.startProcess(userId, definitionKey, supplierEntry);
        } else {
            supplierEntry.setEntryState(1);
            iSupplierEntryService.save(supplierEntry);
        }
    }

    /**
     * 编辑供应商信息
     * @param supplier
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSupplierInfoAll(Supplier supplier) {
        //修改供应商基本上信息
        SupplierInfoVO supplierInfo = supplier.getSupplierInfo();
        this.updateById(supplierInfo.convertToEntity());
        //修改供应商联系人信息
        SupplierLinkmanVO supplierLinkman = supplier.getSupplierLinkman();
        //当联系人不存在，编辑时增加联系人
        if(StringUtils.isEmpty(supplierLinkman.getLinkmanId())){
            supplierLinkman.setLinkmanId(supplierInfo.getLinkmanId());
            supplierLinkman.setSupplierCode(supplierInfo.getSupplierCode());
        }
        iSupplierLinkmanService.saveOrUpdate(supplierLinkman.convertToEntity());
        //修改附件信息
        List<SupplierAccessoryVO> list = supplier.getSupplierAccessory();
        list.forEach(parm->{
            if(StringUtils.isEmpty(parm.getAccessoryId())){
                parm.setAccessoryId(UUIDUtils.get());
                parm.setSupplierCode(supplierInfo.getSupplierCode());
                supplierAccessoryService.save(parm.convertToEntity());
            }else {
                parm.setSupplierCode(supplierInfo.getSupplierCode());
                supplierAccessoryService.updateById(parm.convertToEntity());
            }
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertSupplierInfoType(Supplier supplier) {
        //新增供应商信息
        SupplierInfoVO supplierInfo = supplier.getSupplierInfo();
        String supplierCode = supplierInfo.getSupplierCode();
        //查询之前的供应商类型
        String supplierType = this.getById(supplierCode).getSupplierType();
        //获得新增的供应商类型
        String supplierTypeNew = supplierInfo.getSupplierType();
        supplierInfo.setSupplierType(supplierType+","+supplierTypeNew);
        this.updateById(supplierInfo.convertToEntity());
        //修改供应商准入中供应商的类型
        SupplierEntry supplierEntry = new SupplierEntry();
        supplierEntry.setSupplierCode(supplierInfo.getSupplierCode());
        supplierEntry.setSupplierType(supplierType+","+supplierTypeNew);
        iSupplierEntryService.updateById(supplierEntry);
        return supplierInfo.getSupplierCode();
    }

    /**
     * 查询相对应供应商类型下的供应商编码
     * @return
     */
    @Override
    public PageVO<YyGyslist> querySupplierCode(PageVO<YyGyslist> page,String typeId,String name) {
        return baseMapper.querySupplierCode(page,typeId,name);
    }


    /**
     * 查询全部供应商类型
     * @return
     */
    @Override
    public List<YyGyslist> querySupplierType(){
        return baseMapper.querySupplierType();
    }

    /**
     * 查询全部供应商信息
     * @return
     */
    @Override
    public List<SupplierInfo> queryAll() {
        List<SupplierInfo> list = this.list(new QueryWrapper<SupplierInfo>().select(SupplierInfo.ColName.supplier_code.toString(),
                                                                SupplierInfo.ColName.supplier_name.toString()));
        return list;
    }

    /**
     * 查询当前是否已存在此供应商类型
     * @param supplierType
     * @return
     */
    @Override
    public Integer getSupplierType(String supplierType) {
        return baseMapper.getSupplierType(supplierType);
    }

    @Override
    public List<YyGyslist> querySupplierName(String name) {
        return baseMapper.querySupplierName(name);
    }

    @Override
    public List<SupplierTypeNum> getSupplierTypeNum() {
        List<SupplierTypeNum> supplierTypeNumList = baseMapper.getSupplierTypeNum();
        return supplierTypeNumList;
    }

    @Override
    public List<SupplierEntryNum> getSupplierEntryNum() {
        List<SupplierEntryNum> supplierEntryNumList = baseMapper.getSupplierEntryNum();
        return supplierEntryNumList;
    }

    @Override
    public List<SupplierBadNum> getSupplierBadNum() {
        List<SupplierBadNum> supplierBadNumList = baseMapper.getSupplierBadNum();
        return supplierBadNumList;
    }

    @Override
    public PageVO<HisMaterialDir> getHisMaterialDir(PageVO<HisMaterialDir> page,String supplierCode, String materialId, String materialName, String factory) {
        PageVO<HisMaterialDir> hisMaterialDirList = baseMapper.getHisMaterialDir(page,supplierCode,materialId,materialName,factory);
        return hisMaterialDirList;
    }

    @Override
    public PageVO<HisDrugDir> getHisDrugDir(PageVO<HisDrugDir> page,String supplierCode, String drugId, String drugName, String factory) {
        return baseMapper.getHisDrugDir(page,supplierCode,drugId,drugName,factory);
    }

    @Override
    public Result getSupplierCode(String supplierCode) {
        //查询系统中是否已存在此供应商
        List<SupplierInfo> supplierInfo = this.list(new QueryWrapper<SupplierInfo>().eq(SupplierInfo.ColName.supplier_code.toString(),supplierCode));
        if(CollectionUtils.isNotEmpty(supplierInfo)){
            return Result.ok("供应商在系统已存在",false);
        }else {
            return Result.ok("供应商在系统不存在",true);
        }
    }

    /**
     * 查询字典表中的供应商类型名称，供应商性质名称，所属行业名称，供应商规模名称
     * @param supplierInfoVO
     * @return
     */
    private SupplierInfoVO getDictionariesShowName(SupplierInfoVO supplierInfoVO){
        //查询字典表中供应商类型名称
        String supplierType = supplierInfoVO.getSupplierType();
        if(StringUtils.isNotEmpty(supplierType)){
            String supplierTypeName = iSysDictionariesService.getById(supplierType).getDictionariesShowName();
            supplierInfoVO.setSupplierTypeName(supplierTypeName);
        }
        //查询字典表中供应商性质名称
        String supplierNature = supplierInfoVO.getSupplierNature();
        if(StringUtils.isNotEmpty(supplierNature)){
            String supplierNatureName = iSysDictionariesService.getById(supplierNature).getDictionariesShowName();
            supplierInfoVO.setSupplierNatureName(supplierNatureName);
        }
        //查询字典表中供应商所属行业名称
        String supplierIndustry = supplierInfoVO.getSupplierIndustry();
        if(StringUtils.isNotEmpty(supplierIndustry)){
            String supplierIndustryName = iSysDictionariesService.getById(supplierIndustry).getDictionariesShowName();
            supplierInfoVO.setSupplierIndustryName(supplierIndustryName);
        }
        ////查询字典表中供应商规模名称
        String supplierScale = supplierInfoVO.getSupplierScale();
        if(StringUtils.isNotEmpty(supplierScale)){
            String supplierScaleName = iSysDictionariesService.getById(supplierScale).getDictionariesShowName();
            supplierInfoVO.setSupplierScaleName(supplierScaleName);
        }
        //返回营业执照的存放路径
        if(StringUtils.isNotEmpty(supplierInfoVO.getBusinessLicense())){
            SysUploads sysUploads = iSysUploadsService.getById(supplierInfoVO.getBusinessLicense());
            String savePath = sysUploads.getSavePath();
            String fileName = sysUploads.getFileName();
            supplierInfoVO.setSavePath(InitDataListener.uploadsUrl + savePath + fileName);
        }
        return supplierInfoVO;
    }

    @Override
    public SupplierInfo getSupplierBaseInfo(String supplierCode) {
        return baseMapper.getSupplierBaseInfo(supplierCode);
    }

    @Override
    public PageVO<HisInboundPay> getHisInboundPay(PageVO<HisInboundPay> page, String supplierCode, Integer mainType, String goodsName, String factoryName) {
        return baseMapper.getHisInboundPay(page,supplierCode,mainType,goodsName,factoryName);
    }

    @Override
    public List<String> getSupplierCodeType(String supplierCode) {
        List<String> supplierTypes = new ArrayList<>();
        List<SupplierInfo> supplierInfos = this.list(new QueryWrapper<SupplierInfo>().eq(SupplierInfo.ColName.supplier_code.toString(),supplierCode));
        if(CollectionUtils.isNotEmpty(supplierInfos)){
            supplierInfos.forEach(param->{
                String supplierType = param.getSupplierType();
                supplierTypes.add(supplierType);
            });
        }
        return supplierTypes;
    }

    @Override
    public Supplier getSupplierInfo(String supplierCode) {
        Supplier supplier = new Supplier();
        //查询supplierCode所对应的供应商信息
        SupplierInfo supplierInfoVO = this.getById(supplierCode);
        //查询供应商的准入状态
        Integer entryState = iSupplierEntryService.getOne(new QueryWrapper<SupplierEntry>().eq(SupplierEntry.ColName.supplier_code.toString(),supplierCode)).getEntryState();
        supplierInfoVO.setEntryState(entryState);
        supplier.setSupplierInfo(supplierInfoVO.convertToVO());

        //查询supplierCode所对应的供应商的联系人信息
        SupplierLinkmanVO supplierLinkmanVO = iSupplierLinkmanService.getSavePath(supplierInfoVO.getLinkmanId());
        supplier.setSupplierLinkman(supplierLinkmanVO);

        //查询supplierCode所对应的附件信息
        List<SupplierAccessoryVO> list = iSupplierAccessoryService.querySupplierAccessoryPath(supplierCode);
        supplier.setSupplierAccessory(list);
        return supplier;
    }

    @Override
    public List<SupplierInfo> getSupplierEntryAll() {
        List<SupplierInfo> list = baseMapper.getSupplierEntryAll();
        return list;
    }
}
